/**
 * 画布管理器 - 处理图片显示和区域选择
 */

class CanvasManager {
    constructor(containerId, callbacks = {}) {
        this.containerId = containerId;
        this.callbacks = callbacks;
        
        // 画布状态
        this.image = null;
        this.imageLoaded = false;
        this.scale = 1;
        this.offsetX = 0;
        this.offsetY = 0;
        
        // 交互模式
        this.mode = 'region'; // 'region' 或 'calibration'
        
        // 区域选择状态
        this.isSelecting = false;
        this.startX = 0;
        this.startY = 0;
        this.currentSelection = null;
        this.regions = [];
        
        // 标定点状态
        this.calibrationPoints = [];
        
        // DOM元素
        this.container = null;
        this.imageCanvas = null;
        this.overlayCanvas = null;
        this.imageCtx = null;
        this.overlayCtx = null;
        
        // 鼠标状态
        this.mousePos = { x: 0, y: 0 };
        
        this.init();
    }
    
    /**
     * 初始化画布
     */
    init() {
        this.container = document.getElementById(this.containerId);
        this.imageCanvas = document.getElementById('image-canvas');
        this.overlayCanvas = document.getElementById('overlay-canvas');
        
        if (!this.container || !this.imageCanvas || !this.overlayCanvas) {
            console.error('画布元素未找到');
            return;
        }
        
        this.imageCtx = this.imageCanvas.getContext('2d');
        this.overlayCtx = this.overlayCanvas.getContext('2d');
        
        // 绑定事件
        this.bindEvents();
        
        // 初始化画布尺寸
        this.resizeCanvas();
        
        console.log('画布管理器初始化完成');
    }
    
    /**
     * 绑定鼠标事件
     */
    bindEvents() {
        // 鼠标按下
        this.imageCanvas.addEventListener('mousedown', (e) => {
            this.handleMouseDown(e);
        });
        
        // 鼠标移动
        this.imageCanvas.addEventListener('mousemove', (e) => {
            this.handleMouseMove(e);
        });
        
        // 鼠标松开
        this.imageCanvas.addEventListener('mouseup', (e) => {
            this.handleMouseUp(e);
        });
        
        // 鼠标离开画布
        this.imageCanvas.addEventListener('mouseleave', () => {
            this.handleMouseLeave();
        });
        
        // 滚轮缩放
        this.imageCanvas.addEventListener('wheel', (e) => {
            e.preventDefault();
            this.handleWheel(e);
        });
        
        // 窗口大小改变
        window.addEventListener('resize', () => {
            this.resizeCanvas();
        });
    }
    
    /**
     * 加载图片
     */
    loadImage(imageSrc) {
        const img = new Image();
        img.onload = () => {
            this.image = img;
            this.imageLoaded = true;
            
            // 调整画布尺寸适应图片
            this.fitImageToCanvas();
            
            // 显示画布
            this.showCanvas();
            
            // 绘制图片
            this.drawImage();
            
            console.log('图片加载完成:', img.width, 'x', img.height);
        };
        
        img.onerror = () => {
            console.error('图片加载失败');
            if (this.callbacks.onError) {
                this.callbacks.onError('图片加载失败');
            }
        };
        
        img.src = imageSrc;
    }
    
    /**
     * 调整画布尺寸
     */
    resizeCanvas() {
        const containerRect = this.container.getBoundingClientRect();
        const width = containerRect.width;
        const height = Math.max(containerRect.height, 400);
        
        // 设置画布尺寸
        this.imageCanvas.width = width;
        this.imageCanvas.height = height;
        this.overlayCanvas.width = width;
        this.overlayCanvas.height = height;
        
        // 重新绘制
        if (this.imageLoaded) {
            this.drawImage();
            this.drawRegions();
        }
    }
    
    /**
     * 适应图片到画布
     */
    fitImageToCanvas() {
        if (!this.image) return;
        
        const containerRect = this.container.getBoundingClientRect();
        const containerWidth = containerRect.width - 20; // 留边距
        const containerHeight = Math.max(containerRect.height, 400) - 20;
        
        const imageAspectRatio = this.image.width / this.image.height;
        const containerAspectRatio = containerWidth / containerHeight;
        
        if (imageAspectRatio > containerAspectRatio) {
            // 图片更宽，以宽度为准
            this.scale = containerWidth / this.image.width;
        } else {
            // 图片更高，以高度为准
            this.scale = containerHeight / this.image.height;
        }
        
        // 居中显示
        const scaledWidth = this.image.width * this.scale;
        const scaledHeight = this.image.height * this.scale;
        this.offsetX = (this.imageCanvas.width - scaledWidth) / 2;
        this.offsetY = (this.imageCanvas.height - scaledHeight) / 2;
        
        // 更新缩放显示
        this.updateZoomDisplay();
    }
    
    /**
     * 显示画布
     */
    showCanvas() {
        this.imageCanvas.classList.remove('hidden');
        this.overlayCanvas.classList.remove('hidden');
    }
    
    /**
     * 绘制图片
     */
    drawImage() {
        if (!this.image || !this.imageLoaded) return;
        
        // 清空画布
        this.imageCtx.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);
        
        // 绘制图片
        const scaledWidth = this.image.width * this.scale;
        const scaledHeight = this.image.height * this.scale;
        
        this.imageCtx.drawImage(
            this.image,
            this.offsetX,
            this.offsetY,
            scaledWidth,
            scaledHeight
        );
    }
    
    /**
     * 绘制区域覆盖层
     */
    drawRegions() {
        // 清空覆盖层
        this.overlayCtx.clearRect(0, 0, this.overlayCanvas.width, this.overlayCanvas.height);
        
        // 根据模式绘制相应内容
        if (this.mode === 'region') {
            // 区域模式：只绘制区域框，不显示标定点
            this.regions.forEach((region, index) => {
                this.drawRegionBox(region, index + 1);
            });
        } else if (this.mode === 'calibration') {
            // 标定模式：只绘制标定点，不显示区域框
            this.calibrationPoints.forEach((point, index) => {
                this.drawCalibrationPoint(point, index + 1);
            });
        }
        
        // 绘制当前选择框
        if (this.currentSelection && this.mode === 'region') {
            this.drawSelectionBox(this.currentSelection);
        }
    }
    
    /**
     * 绘制区域框
     */
    drawRegionBox(region, regionNumber) {
        const canvasCoords = this.imageToCanvasCoords(region);
        
        this.overlayCtx.strokeStyle = '#0d9488'; // brand-teal
        this.overlayCtx.fillStyle = 'rgba(13, 148, 136, 0.15)';
        this.overlayCtx.lineWidth = 2;
        
        // 绘制填充区域
        this.overlayCtx.fillRect(
            canvasCoords.x1, canvasCoords.y1,
            canvasCoords.x2 - canvasCoords.x1,
            canvasCoords.y2 - canvasCoords.y1
        );
        
        // 绘制边框
        this.overlayCtx.strokeRect(
            canvasCoords.x1, canvasCoords.y1,
            canvasCoords.x2 - canvasCoords.x1,
            canvasCoords.y2 - canvasCoords.y1
        );
        
        // 如果有温度数据，显示温度信息
        if (region.temperatureData) {
            this.drawTemperatureInfo(canvasCoords, region.temperatureData, regionNumber);
        } else {
            // 只绘制区域编号
            this.drawRegionNumber(canvasCoords, regionNumber);
        }
    }
    
    /**
     * 绘制区域编号
     */
    drawRegionNumber(canvasCoords, regionNumber) {
        this.overlayCtx.fillStyle = '#0d9488';
        this.overlayCtx.font = 'bold 14px Inter';
        this.overlayCtx.textAlign = 'center';
        this.overlayCtx.textBaseline = 'middle';
        
        const centerX = (canvasCoords.x1 + canvasCoords.x2) / 2;
        const centerY = (canvasCoords.y1 + canvasCoords.y2) / 2;
        
        // 绘制白色描边
        this.overlayCtx.strokeStyle = 'white';
        this.overlayCtx.lineWidth = 3;
        this.overlayCtx.strokeText(`${regionNumber}`, centerX, centerY);
        
        // 绘制文字
        this.overlayCtx.fillText(`${regionNumber}`, centerX, centerY);
    }
    
    /**
     * 绘制温度信息
     */
    drawTemperatureInfo(canvasCoords, tempData, regionNumber) {
        const centerX = (canvasCoords.x1 + canvasCoords.x2) / 2;
        const centerY = (canvasCoords.y1 + canvasCoords.y2) / 2;
        const width = canvasCoords.x2 - canvasCoords.x1;
        const height = canvasCoords.y2 - canvasCoords.y1;
        
        // 准备温度文本
        const tempTexts = [
            `区域 ${regionNumber}`,
            `最低: ${tempData.min_temp.toFixed(1)}°C`,
            `最高: ${tempData.max_temp.toFixed(1)}°C`,
            `平均: ${tempData.avg_temp.toFixed(1)}°C`
        ];
        
        // 计算文本框尺寸
        this.overlayCtx.font = '12px Inter';
        const textHeight = 16;
        const padding = 8;
        const boxHeight = tempTexts.length * textHeight + padding * 2;
        
        let maxTextWidth = 0;
        tempTexts.forEach(text => {
            const textWidth = this.overlayCtx.measureText(text).width;
            if (textWidth > maxTextWidth) maxTextWidth = textWidth;
        });
        const boxWidth = maxTextWidth + padding * 2;
        
        // 计算信息框位置（区域右上角）
        let infoX = canvasCoords.x2 + 5;
        let infoY = canvasCoords.y1;
        
        // 边界检查，确保不超出画布
        if (infoX + boxWidth > this.overlayCanvas.width) {
            infoX = canvasCoords.x1 - boxWidth - 5; // 显示在左侧
        }
        if (infoY + boxHeight > this.overlayCanvas.height) {
            infoY = this.overlayCanvas.height - boxHeight - 5;
        }
        
        // 绘制背景框
        this.overlayCtx.fillStyle = 'rgba(13, 148, 136, 0.95)';
        this.overlayCtx.fillRect(infoX, infoY, boxWidth, boxHeight);
        
        // 绘制边框
        this.overlayCtx.strokeStyle = '#0d9488';
        this.overlayCtx.lineWidth = 1;
        this.overlayCtx.strokeRect(infoX, infoY, boxWidth, boxHeight);
        
        // 绘制温度文字
        this.overlayCtx.fillStyle = 'white';
        this.overlayCtx.font = 'bold 12px Inter';
        this.overlayCtx.textAlign = 'left';
        this.overlayCtx.textBaseline = 'top';
        
        tempTexts.forEach((text, index) => {
            const textY = infoY + padding + index * textHeight;
            
            // 第一行（区域编号）使用不同颜色
            if (index === 0) {
                this.overlayCtx.fillStyle = '#fbbf24'; // amber-400
            } else {
                this.overlayCtx.fillStyle = 'white';
            }
            
            this.overlayCtx.fillText(text, infoX + padding, textY);
        });
        
        // 绘制最高最低温度位置标记
        this.drawTemperaturePositionMarkers(canvasCoords, tempData);
    }
    
    /**
     * 绘制最高最低温度位置标记
     */
    drawTemperaturePositionMarkers(regionCoords, tempData) {
        // 將圖像絕對坐標轉換為畫布坐標
        const minPosCanvas = this.imageToCanvasCoords({
            x1: tempData.min_position.x, y1: tempData.min_position.y,
            x2: tempData.min_position.x, y2: tempData.min_position.y
        });
        
        const maxPosCanvas = this.imageToCanvasCoords({
            x1: tempData.max_position.x, y1: tempData.max_position.y,
            x2: tempData.max_position.x, y2: tempData.max_position.y
        });
        
        // 最低温度位置（蓝色圆点）
        this.overlayCtx.beginPath();
        this.overlayCtx.arc(minPosCanvas.x1, minPosCanvas.y1, 4, 0, 2 * Math.PI);
        this.overlayCtx.fillStyle = '#3b82f6'; // blue-500
        this.overlayCtx.fill();
        this.overlayCtx.strokeStyle = 'white';
        this.overlayCtx.lineWidth = 2;
        this.overlayCtx.stroke();
        
        // 最高温度位置（红色圆点）
        this.overlayCtx.beginPath();
        this.overlayCtx.arc(maxPosCanvas.x1, maxPosCanvas.y1, 4, 0, 2 * Math.PI);
        this.overlayCtx.fillStyle = '#ef4444'; // red-500
        this.overlayCtx.fill();
        this.overlayCtx.strokeStyle = 'white';
        this.overlayCtx.lineWidth = 2;
        this.overlayCtx.stroke();
    }
    
    /**
     * 绘制选择框
     */
    drawSelectionBox(selection) {
        this.overlayCtx.strokeStyle = '#059669'; // brand-green
        this.overlayCtx.fillStyle = 'rgba(5, 150, 105, 0.1)';
        this.overlayCtx.lineWidth = 2;
        this.overlayCtx.setLineDash([5, 5]);
        
        const width = selection.x2 - selection.x1;
        const height = selection.y2 - selection.y1;
        
        // 绘制填充
        this.overlayCtx.fillRect(selection.x1, selection.y1, width, height);
        
        // 绘制虚线边框
        this.overlayCtx.strokeRect(selection.x1, selection.y1, width, height);
        
        // 重置线条样式
        this.overlayCtx.setLineDash([]);
    }
    
    /**
     * 绘制标定点
     */
    drawCalibrationPoint(point, pointNumber) {
        // 修复坐标获取问题
        let position = point.position;
        if (!Array.isArray(position) && Array.isArray(point.temperature)) {
            // 数据结构颠倒了，坐标存在temperature字段中
            position = point.temperature;
        }
        // 确保position是数组且有效
        if (!Array.isArray(position) || position.length < 2) {
            console.warn('标定点坐标无效:', point);
            return;
        }
        
        const canvasCoords = this.imageToCanvasCoords({
            x1: position[0], y1: position[1],
            x2: position[0], y2: position[1]
        });
        
        const centerX = canvasCoords.x1;
        const centerY = canvasCoords.y1;
        const radius = 8;
        
        // 绘制外圈
        this.overlayCtx.beginPath();
        this.overlayCtx.arc(centerX, centerY, radius + 2, 0, 2 * Math.PI);
        this.overlayCtx.fillStyle = '#3b82f6'; // blue-500
        this.overlayCtx.fill();
        
        // 绘制内圈
        this.overlayCtx.beginPath();
        this.overlayCtx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
        this.overlayCtx.fillStyle = 'white';
        this.overlayCtx.fill();
        
        // 绘制点号
        this.overlayCtx.fillStyle = '#3b82f6';
        this.overlayCtx.font = 'bold 10px Inter';
        this.overlayCtx.textAlign = 'center';
        this.overlayCtx.textBaseline = 'middle';
        this.overlayCtx.fillText(`${pointNumber}`, centerX, centerY);
        
        // 绘制温度标签
        let temperature = point.temperature;
        // 修复数据结构错乱问题：如果temperature是数组，使用position作为温度值
        if (Array.isArray(temperature)) {
            temperature = point.position;
        }
        // 如果position是数组，使用temperature作为温度值
        if (Array.isArray(point.position) && typeof temperature === 'number') {
            // 数据结构正常
        } else if (!Array.isArray(point.position) && Array.isArray(temperature)) {
            // 数据结构颠倒了
            temperature = point.position;
        }
        const tempText = `${typeof temperature === 'number' ? temperature.toFixed(1) : temperature}°C`;
        const labelX = centerX + 15;
        const labelY = centerY - 10;
        
        // 背景框
        this.overlayCtx.font = '12px Inter';
        const textWidth = this.overlayCtx.measureText(tempText).width;
        this.overlayCtx.fillStyle = 'rgba(59, 130, 246, 0.9)';
        this.overlayCtx.fillRect(labelX - 2, labelY - 8, textWidth + 4, 16);
        
        // 文字
        this.overlayCtx.fillStyle = 'white';
        this.overlayCtx.textAlign = 'left';
        this.overlayCtx.fillText(tempText, labelX, labelY);
    }
    
    /**
     * 处理鼠标按下事件
     */
    handleMouseDown(e) {
        if (!this.imageLoaded) return;
        
        const rect = this.imageCanvas.getBoundingClientRect();
        const canvasX = e.clientX - rect.left;
        const canvasY = e.clientY - rect.top;
        
        // 检查是否在图片范围内
        if (!this.isPointInImage(canvasX, canvasY)) return;
        
        if (this.mode === 'calibration') {
            // 标定模式：单击添加标定点
            const imageCoords = this.canvasToImageCoords({
                x1: canvasX, y1: canvasY, x2: canvasX, y2: canvasY
            });
            
            if (this.callbacks.onCalibrationPointClicked) {
                this.callbacks.onCalibrationPointClicked({
                    x: Math.round(imageCoords.x1),
                    y: Math.round(imageCoords.y1)
                });
            }
            console.log('标定点点击:', Math.round(imageCoords.x1), Math.round(imageCoords.y1));
        } else {
            // 区域选择模式：拖拽选择区域
            this.isSelecting = true;
            this.startX = canvasX;
            this.startY = canvasY;
            
            this.currentSelection = {
                x1: canvasX,
                y1: canvasY,
                x2: canvasX,
                y2: canvasY
            };
            
            console.log('开始选择区域:', this.startX, this.startY);
        }
    }
    
    /**
     * 处理鼠标移动事件
     */
    handleMouseMove(e) {
        const rect = this.imageCanvas.getBoundingClientRect();
        const canvasX = e.clientX - rect.left;
        const canvasY = e.clientY - rect.top;
        
        // 更新鼠标坐标显示
        this.updateMouseCoords(canvasX, canvasY);
        
        // 只在区域选择模式下处理拖拽
        if (this.mode !== 'region' || !this.isSelecting || !this.imageLoaded) return;
        
        // 更新选择框
        this.currentSelection.x2 = canvasX;
        this.currentSelection.y2 = canvasY;
        
        // 重新绘制
        this.drawRegions();
    }
    
    /**
     * 处理鼠标松开事件
     */
    handleMouseUp(e) {
        // 只在区域选择模式下处理
        if (this.mode !== 'region' || !this.isSelecting || !this.currentSelection) return;
        
        this.isSelecting = false;
        
        // 计算选择区域大小
        const width = Math.abs(this.currentSelection.x2 - this.currentSelection.x1);
        const height = Math.abs(this.currentSelection.y2 - this.currentSelection.y1);
        
        // 检查区域是否足够大（至少10x10像素）
        if (width < 10 || height < 10) {
            this.currentSelection = null;
            this.drawRegions();
            return;
        }
        
        // 标准化坐标（确保x1 < x2, y1 < y2）
        const normalizedSelection = {
            x1: Math.min(this.currentSelection.x1, this.currentSelection.x2),
            y1: Math.min(this.currentSelection.y1, this.currentSelection.y2),
            x2: Math.max(this.currentSelection.x1, this.currentSelection.x2),
            y2: Math.max(this.currentSelection.y1, this.currentSelection.y2)
        };
        
        // 转换为图片坐标
        const imageCoords = this.canvasToImageCoords(normalizedSelection);
        
        // 添加到区域列表
        const region = {
            ...imageCoords,
            width: imageCoords.x2 - imageCoords.x1,
            height: imageCoords.y2 - imageCoords.y1
        };
        
        this.regions.push(region);
        
        // 清空当前选择
        this.currentSelection = null;
        
        // 重新绘制
        this.drawRegions();
        
        // 触发回调
        if (this.callbacks.onRegionSelected) {
            this.callbacks.onRegionSelected(region);
        }
        
        console.log('区域选择完成:', region);
    }
    
    /**
     * 处理鼠标离开事件
     */
    handleMouseLeave() {
        // 清空鼠标坐标显示
        const coordsElement = document.getElementById('mouse-coords');
        if (coordsElement) {
            coordsElement.textContent = '-';
        }
    }
    
    /**
     * 处理滚轮缩放
     */
    handleWheel(e) {
        if (!this.imageLoaded) return;
        
        // 在區域模式下禁用縮放功能
        if (this.mode === 'region') {
            return;
        }
        
        const rect = this.imageCanvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;
        
        // 计算缩放中心点（图片坐标）
        const imageMouseX = (mouseX - this.offsetX) / this.scale;
        const imageMouseY = (mouseY - this.offsetY) / this.scale;
        
        // 缩放因子
        const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
        const newScale = Math.max(0.1, Math.min(5, this.scale * zoomFactor));
        
        if (newScale !== this.scale) {
            // 更新偏移量，保持鼠标位置不变
            this.offsetX = mouseX - imageMouseX * newScale;
            this.offsetY = mouseY - imageMouseY * newScale;
            this.scale = newScale;
            
            // 重新绘制
            this.drawImage();
            this.drawRegions();
            
            // 更新缩放显示
            this.updateZoomDisplay();
        }
    }
    
    /**
     * 更新鼠标坐标显示
     */
    updateMouseCoords(canvasX, canvasY) {
        const coordsElement = document.getElementById('mouse-coords');
        if (!coordsElement) return;
        
        if (this.imageLoaded && this.isPointInImage(canvasX, canvasY)) {
            const imageCoords = this.canvasToImageCoords({
                x1: canvasX, y1: canvasY, x2: canvasX, y2: canvasY
            });
            coordsElement.textContent = `(${Math.round(imageCoords.x1)}, ${Math.round(imageCoords.y1)})`;
        } else {
            coordsElement.textContent = '-';
        }
    }
    
    /**
     * 更新缩放显示
     */
    updateZoomDisplay() {
        const zoomElement = document.getElementById('zoom-level');
        if (zoomElement) {
            zoomElement.textContent = `${Math.round(this.scale * 100)}%`;
        }
    }
    
    /**
     * 检查点是否在图片范围内
     */
    isPointInImage(canvasX, canvasY) {
        if (!this.imageLoaded) return false;
        
        const scaledWidth = this.image.width * this.scale;
        const scaledHeight = this.image.height * this.scale;
        
        return canvasX >= this.offsetX && 
               canvasX <= this.offsetX + scaledWidth &&
               canvasY >= this.offsetY && 
               canvasY <= this.offsetY + scaledHeight;
    }
    
    /**
     * 画布坐标转图片坐标
     */
    canvasToImageCoords(canvasCoords) {
        return {
            x1: Math.round((canvasCoords.x1 - this.offsetX) / this.scale),
            y1: Math.round((canvasCoords.y1 - this.offsetY) / this.scale),
            x2: Math.round((canvasCoords.x2 - this.offsetX) / this.scale),
            y2: Math.round((canvasCoords.y2 - this.offsetY) / this.scale)
        };
    }
    
    /**
     * 图片坐标转画布坐标
     */
    imageToCanvasCoords(imageCoords) {
        return {
            x1: imageCoords.x1 * this.scale + this.offsetX,
            y1: imageCoords.y1 * this.scale + this.offsetY,
            x2: imageCoords.x2 * this.scale + this.offsetX,
            y2: imageCoords.y2 * this.scale + this.offsetY
        };
    }
    
    /**
     * 重置缩放
     */
    resetZoom() {
        if (!this.imageLoaded) return;
        
        this.fitImageToCanvas();
        this.drawImage();
        this.drawRegions();
        
        console.log('缩放已重置');
    }
    
    /**
     * 设置交互模式
     */
    setMode(mode) {
        this.mode = mode;
        
        // 切换模式时清空当前选择
        this.currentSelection = null;
        this.isSelecting = false;
        
        // 更新画布光标样式
        if (mode === 'calibration') {
            this.imageCanvas.style.cursor = 'crosshair';
        } else {
            this.imageCanvas.style.cursor = 'crosshair';
        }
        
        this.drawRegions();
        console.log('切换到模式:', mode);
    }
    
    /**
     * 获取当前模式
     */
    getMode() {
        return this.mode;
    }
    
    /**
     * 添加标定点
     */
    addCalibrationPoint(point) {
        this.calibrationPoints.push(point);
        this.drawRegions();
        console.log('标定点已添加:', point);
    }
    
    /**
     * 更新标定点列表
     */
    updateCalibrationPoints(points) {
        this.calibrationPoints = [...points];
        this.drawRegions();
    }
    
    /**
     * 清空所有标定点
     */
    clearCalibrationPoints() {
        this.calibrationPoints = [];
        this.drawRegions();
        console.log('所有标定点已清空');
    }
    
    /**
     * 移除指定标定点
     */
    removeCalibrationPoint(index) {
        if (index >= 0 && index < this.calibrationPoints.length) {
            this.calibrationPoints.splice(index, 1);
            this.drawRegions();
            
            if (this.callbacks.onCalibrationPointRemoved) {
                this.callbacks.onCalibrationPointRemoved(index);
            }
        }
    }
    
    /**
     * 获取当前所有标定点
     */
    getCalibrationPoints() {
        return [...this.calibrationPoints];
    }
    
    /**
     * 清空所有区域
     */
    clearRegions() {
        this.regions = [];
        this.currentSelection = null;
        this.drawRegions();
        console.log('所有区域已清空');
    }
    
    /**
     * 更新区域列表
     */
    updateRegions(regions) {
        this.regions = [...regions];
        this.drawRegions();
    }
    
    /**
     * 更新区域并显示温度信息
     */
    updateRegionsWithTemperature(regionsWithTemp) {
        this.regions = [...regionsWithTemp];
        this.drawRegions();
        console.log('区域温度信息已更新');
    }
    
    /**
     * 移除指定区域
     */
    removeRegion(index) {
        if (index >= 0 && index < this.regions.length) {
            this.regions.splice(index, 1);
            this.drawRegions();
            
            if (this.callbacks.onRegionRemoved) {
                this.callbacks.onRegionRemoved(index);
            }
        }
    }
    
    /**
     * 获取当前所有区域
     */
    getRegions() {
        return [...this.regions];
    }
    
    /**
     * 获取图片尺寸
     */
    getImageDimensions() {
        if (!this.image) return null;
        return {
            width: this.image.width,
            height: this.image.height
        };
    }
    
    /**
     * 获取当前缩放级别
     */
    getZoomLevel() {
        return this.scale;
    }
    
    /**
     * 设置缩放级别
     */
    setZoomLevel(scale) {
        if (!this.imageLoaded) return;
        
        this.scale = Math.max(0.1, Math.min(5, scale));
        
        // 重新计算偏移量（保持居中）
        const scaledWidth = this.image.width * this.scale;
        const scaledHeight = this.image.height * this.scale;
        this.offsetX = (this.imageCanvas.width - scaledWidth) / 2;
        this.offsetY = (this.imageCanvas.height - scaledHeight) / 2;
        
        this.drawImage();
        this.drawRegions();
        this.updateZoomDisplay();
    }
    
    /**
     * 导出当前画布为图片
     */
    exportCanvas() {
        if (!this.imageLoaded) return null;
        
        // 创建合成画布
        const exportCanvas = document.createElement('canvas');
        exportCanvas.width = this.imageCanvas.width;
        exportCanvas.height = this.imageCanvas.height;
        const exportCtx = exportCanvas.getContext('2d');
        
        // 绘制图片
        exportCtx.drawImage(this.imageCanvas, 0, 0);
        
        // 绘制区域覆盖层
        exportCtx.drawImage(this.overlayCanvas, 0, 0);
        
        return exportCanvas.toDataURL('image/png');
    }
    
    /**
     * 清理资源
     */
    cleanup() {
        this.image = null;
        this.imageLoaded = false;
        this.regions = [];
        this.calibrationPoints = [];
        this.currentSelection = null;
        this.isSelecting = false;
        
        if (this.imageCtx) {
            this.imageCtx.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);
        }
        if (this.overlayCtx) {
            this.overlayCtx.clearRect(0, 0, this.overlayCanvas.width, this.overlayCanvas.height);
        }
        
        console.log('画布管理器已清理');
    }
}

// ==================== 工具函数 ====================

/**
 * 计算两点之间的距离
 */
function calculateDistance(x1, y1, x2, y2) {
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}

/**
 * 检查矩形是否相交
 */
function rectanglesIntersect(rect1, rect2) {
    return !(rect1.x2 < rect2.x1 || 
             rect2.x2 < rect1.x1 || 
             rect1.y2 < rect2.y1 || 
             rect2.y2 < rect1.y1);
}

/**
 * 计算矩形面积
 */
function calculateArea(rect) {
    return (rect.x2 - rect.x1) * (rect.y2 - rect.y1);
}

/**
 * 标准化矩形坐标
 */
function normalizeRectangle(x1, y1, x2, y2) {
    return {
        x1: Math.min(x1, x2),
        y1: Math.min(y1, y2),
        x2: Math.max(x1, x2),
        y2: Math.max(y1, y2)
    };
}

// 导出到全局作用域
window.CanvasManager = CanvasManager;